package com.sharemob.tinchat.lib;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Base64;
import android.util.Log;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.Toast;

import com.sharemob.tinchat.base.LocalSheetDialog;
import com.sharemob.tinchat.base.LocalSheetDialog.OnSheetItemClickListener;
import com.sharemob.tinchat.base.LocalSheetDialog.SheetItemColor;
import com.sharemob.tinchat.lib.common.AsyncHttpRequest;
import com.sharemob.tinchat.lib.common.AsyncHttpRequest.RequestCallback;
import com.sharemob.tinchat.lib.common.SMGlobal;
import com.sharemob.tinchat.modules.account.ActivityAccountInfo;

public final class Utils {

	public static void StrictMode(){
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());

		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()
				.build());
	}

	public static void SelectPhotoDialog(Context context){
		
		new LocalSheetDialog(context)
		.builder()
		.setCancelable(false)
		.setCanceledOnTouchOutside(false)
		.addSheetItem("拍照", SheetItemColor.Red,
				new OnSheetItemClickListener() {
					@Override
					public void onClick(int which) {

					}
				})
		.addSheetItem("本地相册", SheetItemColor.Red,
				new OnSheetItemClickListener() {
					@Override
					public void onClick(int which) {

					}
				}).show();
	}
	
	
	public static void setFlickerAnimation(ImageView iv_chat_head) {  
        final Animation animation = new AlphaAnimation(1, 0); // Change alpha from fully visible to invisible  
        animation.setDuration(500); // duration - half a second  
        animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate  
        animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely  
        animation.setRepeatMode(Animation.REVERSE); //   
        iv_chat_head.setAnimation(animation);  
}  
	
	public static void cacheImage(String url,String path){
		StrictMode();
		try {
			File file = new File(path);
			FileOutputStream out = new FileOutputStream(file);

			URL myFileUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();

			byte buff[] = new byte[1024];
			int len = 0;
			while ((len = is.read(buff)) != -1) {
				out.write(buff, 0, len);
			}
			is.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}


	public static Bitmap getDiskBitmap(String pathString){
		Bitmap bitmap = null;  
	    try  
	    {  
	        File file = new File(pathString);  
	        if(file.exists())  
	        {  
	            bitmap = BitmapFactory.decodeFile(pathString);  
	        }  
	    } catch (Exception e)  
	    {  
	    }  
	    return bitmap;
		
	}
	public static Bitmap convertBitMap(String _url) {

		URL url=null;
		try {
			url = new URL(_url);
			Bitmap pngBM = BitmapFactory.decodeStream(url.openStream()); 
			
			return pngBM;
		} catch (Exception e) {
			e.printStackTrace();
		}
		File cache = new File(Environment.getExternalStorageDirectory(), "TinChat");
		
		return null;
	}
	
	 /*
	  * 旋转图片 
	  * @param angle 
	  * @param bitmap 
	  * @return Bitmap 
	  */ 
	   public static Bitmap rotaingImageView(byte[] data) {  
	     //旋转图片 动作   
	     Matrix matrix = new Matrix();
	     matrix.postRotate(90);
	     // 创建新的图片   
	     Bitmap bitmap=  BitmapFactory.decodeByteArray(data, 0, data.length);
	     return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);  
	   }
	   public static final String getVerificationCode(){
		String[] beforeShuffle = new String[] { "0", "1", "2", "3", "4", "5","6", "7", "8", "9" };
		List<String> list = Arrays.asList(beforeShuffle);
		Collections.shuffle(list);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i));
		}
		String afterShuffle = sb.toString();
		String result = afterShuffle.substring(5, 9);
		System.out .print(result) ;
		return result;
	}
	public static Location getLocation(){
		Context context=SMGlobal.getInstance().context;
		LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
		if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){  
            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);  
            return location;
        }else{  
            LocationListener locationListener = new LocationListener() {  
                // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数  
                public void onStatusChanged(String provider, int status, Bundle extras) {  
                      
                }  
                // Provider被enable时触发此函数，比如GPS被打开  
                public void onProviderEnabled(String provider) {  
                      
                }  
                // Provider被disable时触发此函数，比如GPS被关闭   
                public void onProviderDisabled(String provider) {  
                      
                }  
                //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发   
                public void onLocationChanged(Location location) {  
                    if (location != null) {     
                        Log.e("Map", "Location changed : Lat: " + location.getLatitude() + " Lng: "+ location.getLongitude());     
                    }  
                }  
            };  
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000, 0,locationListener);     
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            return location;
        }  
	}
	

	
    /** 
     * 显示Toast消息 
     * @param msg 
     */  
    public static void showToast(String msg){  
    	Toast mToast =Toast.makeText(SMGlobal.getInstance().context, msg, Toast.LENGTH_LONG);  
        mToast.setText(msg);  
        mToast.show();  
    }


    public static Uri getCropPhotoFilePath(){
     	File file = new File(Environment.getExternalStorageDirectory(), "TinChat/tinchat_camera_temp.jpg");
    	Uri imageUri = Uri.fromFile(file);
		return imageUri;
    }
    
    public static Uri getLiveCoverFilePath(){
     	File file = new File(Environment.getExternalStorageDirectory(), "TinChat/tinchat_live_cover.jpg");
    	Uri imageUri = Uri.fromFile(file);
		return imageUri;
    }
    
   
    public static String getVoiceFilePath(){
    	String voicePath=String.format("%s/%s/signatureVoice.3gp", Environment.getExternalStorageDirectory(),"TinChat");
    	return voicePath;
    }
    
    public static String getLiveCoverTempFilePath(){
    	String coverPath=String.format("%s/%s/%s.PNG", Environment.getExternalStorageDirectory(),"TinChat",String.valueOf(System.currentTimeMillis()));
    	return coverPath;
    }
    
    public Bitmap getVideoThumbnail(String filePath) {  
        Bitmap bitmap = null;  
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();  
        try {  
            retriever.setDataSource(filePath);  
            bitmap = retriever.getFrameAtTime();  
        }   
        catch(IllegalArgumentException e) {  
            e.printStackTrace();  
        }   
        catch (RuntimeException e) {  
            e.printStackTrace();  
        }   
        finally {  
            try {  
                retriever.release();  
            }   
            catch (RuntimeException e) {  
                e.printStackTrace();  
            }  
        }  
        return bitmap;  
    }  
    public static String getVideoFilePath(){
    	String videoPath=String.format("%s/%s/tc_video.mp4", Environment.getExternalStorageDirectory(),"TinChat");
    	return videoPath;
    }

  
 

}
